package struts.action;

import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.EventDispatchAction;
import org.apache.struts.util.MessageResources;
import org.springframework.beans.factory.annotation.Autowired;

import util.SystemSettingUtil;
import bean.ResultMessageObject;
import bean.UserObject;

/**
 * 共通错误处理
 */
public class ErrorHandleAction extends EventDispatchAction {

	@Autowired
	UserObject userObject;

	private static final Log log = LogFactory.getLog(ErrorHandleAction.class);

	// 直接被访问的出错消息
	private static final String DIRECT_ACCESS_ERRROR_KEY = "Z3101W0003";

	// 错误log的格式
	protected static final MessageFormat format = new MessageFormat(SystemSettingUtil.getString("boardgame.resource.errorlog.format",
			"session ID:{0} 用户ID:{1} :{2} 功能ID:{3} 错误内容[{4}]"));

	/**
	 * 初期处理
	 * 
	 * @param mapping ActionMapping
	 * @param form ActionForm
	 * @param request HttpServletRequest
	 * @param response HttpServletResponse
	 * @return ActionForward
	 */
	public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		// 因为错误信息是在CustomExceptionHandler类里面通过request存放起来的,
		// 所以没有resultMessage的时候,直接throw IllegalPageOperationException.
		ResultMessageObject resultMessage = (ResultMessageObject) request.getSession().getAttribute(ResultMessageObject.RESULT_MESSAGE_KEY);

		if (resultMessage == null) {
			throw new IllegalPageOperationException(DIRECT_ACCESS_ERRROR_KEY);
		}

		// 取得错误信息内容
		MessageResources mes = getResources(request);
		resultMessage.setTitleMessage(mes.getMessage(resultMessage.getTitleCode(), resultMessage.getArgs()));
		resultMessage.setMessage(mes.getMessage(resultMessage.getCode(), resultMessage.getArgs()));

		if (log.isDebugEnabled()) {
			log.debug(ToStringBuilder.reflectionToString(resultMessage, ToStringStyle.MULTI_LINE_STYLE));
		}

		// 将错误信息存入request
		request.setAttribute(ResultMessageObject.RESULT_MESSAGE_KEY, resultMessage);

		// 将错误信息从session中删除
		request.getSession().removeAttribute(ResultMessageObject.RESULT_MESSAGE_KEY);

		// 如果是系统级错误,记录错误日志
		if (resultMessage.isSyserror() || "Z3101W0001".equals(resultMessage.getTitleCode())) {
			log.error(format.format(new Object[] { request.getSession().getId(), userObject.getUserId(), resultMessage.getFunctionId(),
					ExceptionUtils.getFullStackTrace(resultMessage.getError()) }));
		}

		return mapping.findForward("self");
	}
}
